{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "$ \\sqrt{2} ≈ 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415728$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入您要计算算术平方根的数：2\n",
      "请输入计算精度：100\n",
      "2 的算术平方根为：1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415728\n"
     ]
    }
   ],
   "source": [
    "from decimal import *\n",
    "from _decimal import Decimal\n",
    "from math import log\n",
    "\n",
    "\n",
    "def my_sqrt(value=2, precision=100):\n",
    "    \"\"\"用牛顿迭代法计算一个数的算术平方根，并指定精度\n",
    "\n",
    "    :参数 value:      待计算数，默认为2\n",
    "    :参数 precision:  平方根精度，默认为小数点后100位\n",
    "    :返回值:          返回计算结果\n",
    "\n",
    "    示例：\n",
    "\n",
    "    >>> my_sqrt()\n",
    "    1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415728\n",
    "    >>> get_pow(3, 10)\n",
    "    1.7320508076\n",
    "\n",
    "    \"\"\"\n",
    "    next_value = value/2.0\n",
    "    threshold = 10**(-precision)\n",
    "\n",
    "    while True:\n",
    "        # Decimal函数用户python进行高精度运算\n",
    "        last_value = Decimal((next_value + value/next_value )/2)  # 牛顿迭代法公式\n",
    "        # 如果计算值少于设定的阈值，则认为找到了正确的结果\n",
    "        if abs(Decimal(last_value) - Decimal(next_value)) < threshold:\n",
    "            return Decimal(last_value)\n",
    "        next_value = Decimal(last_value)\n",
    "\n",
    "\n",
    "x = int(input(\"请输入您要计算算术平方根的数：\"))\n",
    "y = int(input(\"请输入计算精度：\"))\n",
    "getcontext().prec = y + int(log(x, 10)//2) + 1\n",
    "\n",
    "a = my_sqrt(x, y)\n",
    "print(f\"{x} 的算术平方根为：{a}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
